// internal/infrastructure/persistence/redis/cache_repository.go
package redis

import (
	"context"
	"encoding/json"
	"gLottery/internal/domain/repository"
	"github.com/go-redis/redis/v8"
	"time"
)

type CacheRepo struct {
	client *redis.Client
}

func NewCacheRepository(client *redis.Client) repository.CacheRepository {
	return &CacheRepo{client: client}
}

func (r *CacheRepo) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
	p, err := json.Marshal(value)
	if err != nil {
		return err
	}
	return r.client.Set(ctx, key, p, expiration).Err()
}

func (r *CacheRepo) Get(ctx context.Context, key string) (string, error) {
	val, err := r.client.Get(ctx, key).Result()
	if err == redis.Nil {
		return "", nil // Key不存在时不作为错误
	}
	return val, err
}

func (r *CacheRepo) Delete(ctx context.Context, keys ...string) error {
	return r.client.Del(ctx, keys...).Err()
}

func (r *CacheRepo) Exists(ctx context.Context, key string) (bool, error) {
	exist, err := r.client.Exists(ctx, key).Result()
	return exist > 0, err
}
